import React, { Component } from "react";
import { Statistic, Card, Row, Col, Avatar, Divider, List } from 'antd';

// http
import http from '../../utils/request';
// charts
// import SasGrade from "./charts/sas";
import { TinyArea, TinyColumn, Rose, Bar, Pie, measureTextWidth } from '@ant-design/plots';
import "./a.scss"


function renderStatistic(containerWidth, text, style) {
  const { width: textWidth, height: textHeight } = measureTextWidth(text, style);
  const R = containerWidth / 2; // r^2 = (w / 2)^2 + (h - offsetY)^2

  let scale = 1;

  if (containerWidth < textWidth) {
    scale = Math.min(Math.sqrt(Math.abs(Math.pow(R, 2) / (Math.pow(textWidth / 2, 2) + Math.pow(textHeight, 2)))), 1);
  }

  const textStyleStr = `width:${containerWidth}px;`;
  return `<div style="${textStyleStr};font-size:${scale}em;line-height:${scale < 1 ? 1 : 'inherit'};">${text}</div>`;
}

class Dashboard extends Component {
    constructor(props){
        super(props);
        this.state = {
          // 访问量
          total_request: null,
          total_request_list: null,
          total_request_today: null,

          // 助手调用
          robot_request: null,
          robot_request_list: null,
          robot_request_today_single: null,
          robot_request_today_many: null,

          // 告警量
          alarm_request: null,
          alarm_request_threshold: null,
          alarm_request_event: null,
          alarm_request_sls: null,
          alarm_request_day_percent: '',
          alarm_request_week_percent: '',

          // 审批量
          approval_request: null,
          approval_request_list: null,
          approval_request_account: null,
          approval_request_domain: null,

          // 业务线告警量
          business_alarm_list: [],

          // 负责人短信量
          cms_alarm_list: [],

          // 云平台账户汇总
          cloud_account_list: [],
        };
    }

    async componentDidMount() {
      this.loadDataTotalRequest()
      this.loadDataRobotRequest()
      this.loadDataAlarmRequest()
      this.loadDataApprovalRequest()
      this.loadDataBusinessAlarmRequest()
      this.loadDataCmsAlarmRequest()
      this.loadDataCloudAccountRequest()

    }

    async loadDataCloudAccountRequest() {
      const requestData = {
        'request_type': 'cloud_account_request',
      }
      await http.get('/dashboard', {params: requestData}).then(response => {
          const cloud_account_list = response.data.data.cloud_account_list
          this.setState({
            cloud_account_list: cloud_account_list,
          })
      })
    }

    async loadDataCmsAlarmRequest() {
      const requestData = {
        'request_type': 'cms_alarm_request',
      }
      await http.get('/dashboard', {params: requestData}).then(response => {
          const cms_alarm_list = response.data.data.cms_alarm_list
          this.setState({
            cms_alarm_list: cms_alarm_list,
          })
      })
    }

    async loadDataBusinessAlarmRequest() {
      const requestData = {
        'request_type': 'business_alarm_request',
      }
      await http.get('/dashboard', {params: requestData}).then(response => {
          const business_alarm_list = response.data.data.business_alarm_list
          this.setState({
            business_alarm_list: business_alarm_list,
          })
      })
    }

    async loadDataAlarmRequest() {
      const requestData = {
        'request_type': 'alarm_request',
      }
      await http.get('/dashboard', {params: requestData}).then(response => {
          const alarm_request = response.data.data.alarm_request
          const alarm_request_threshold = response.data.data.alarm_request_threshold
          const alarm_request_event = response.data.data.alarm_request_event
          const alarm_request_sls = response.data.data.alarm_request_sls
          const alarm_request_day_percent = response.data.data.alarm_request_day_percent
          const alarm_request_week_percent = response.data.data.alarm_request_week_percent
          this.setState({
            alarm_request: alarm_request,
            alarm_request_threshold: alarm_request_threshold,
            alarm_request_event: alarm_request_event,
            alarm_request_sls: alarm_request_sls,
            alarm_request_day_percent: alarm_request_day_percent,
            alarm_request_week_percent: alarm_request_week_percent,
          })
      })
    }

    async loadDataApprovalRequest() {
      const requestData = {
        'request_type': 'approval_request',
      }
      await http.get('/dashboard', {params: requestData}).then(response => {
          const approval_request = response.data.data.approval_request
          const approval_request_list = response.data.data.approval_request_list
          const approval_request_account = response.data.data.approval_request_account
          const approval_request_domain = response.data.data.approval_request_domain
          this.setState({
              approval_request: approval_request,
              approval_request_list: approval_request_list,
              approval_request_account: approval_request_account,
              approval_request_domain: approval_request_domain,
          })
      })
    }

    async loadDataTotalRequest() {
      const requestData = {
        'request_type': 'total_request',
      }
      await http.get('/dashboard', {params: requestData}).then(response => {
          const total_request = response.data.data.total_request
          const total_request_list = response.data.data.total_request_list
          const total_request_today = response.data.data.total_request_today
          this.setState({
              total_request: total_request,
              total_request_list: total_request_list,
              total_request_today: total_request_today,
          })
      })
    }

    async loadDataRobotRequest() {
      const requestData = {
        'request_type': 'total_robot',
      }
      await http.get('/dashboard', {params: requestData}).then(response => {
          const robot_request = response.data.data.robot_request
          const robot_request_list = response.data.data.robot_request_list
          const robot_request_today_single = response.data.data.robot_request_today_single
          const robot_request_today_many = response.data.data.robot_request_today_many
          this.setState({
              robot_request: robot_request,
              robot_request_list: robot_request_list,
              robot_request_today_single: robot_request_today_single,
              robot_request_today_many: robot_request_today_many
          })
      })
    }

    render(){
      const { total_request, total_request_list, total_request_today, robot_request, robot_request_list, robot_request_today_single, robot_request_today_many,
              approval_request, approval_request_list, approval_request_account, approval_request_domain,
              alarm_request, alarm_request_threshold, alarm_request_event, alarm_request_sls, alarm_request_day_percent, alarm_request_week_percent,
              business_alarm_list, cms_alarm_list, cloud_account_list
      } = this.state

      const requestConfig = {
        height: 40,
        // autoFit: false,
        data: total_request_list,
        smooth: true,
        color: '#E5EDFE',
        pattern: {
          type: 'line',
          cfg: {
            stroke: '#5B8FF9',
          },
        },
      };
      const robotConfig = {
        height: 40,
        // autoFit: false,
        data: robot_request_list,
        // areaStyle: {
        //   fill: '#9500B8',  
        //   lineOpacity: 1,
        //   lineWidth: 1,
        //   strokeOpacity: 0,
        //   stroke: 'black',
        // },
        // tooltip: {
        //   customContent: function (x, data) {
        //     return `NO.${x}: ${data[0]?.data?.y.toFixed(2)}`;
        //   },
        // },
      };
      const approvalConfig = {
        height: 40,
        // autoFit: false,
        data: approval_request_list,
        // smooth: true,
        areaStyle: {
          fill: '#9500B8',  
          lineOpacity: 1,
          lineWidth: 1,
          strokeOpacity: 0,
          stroke: 'black',

        },
      };
      const businessAlarmConfig = {
        data: business_alarm_list,
        xField: 'type',
        yField: 'value',
        seriesField: 'type',
        radius: 0.9,
        label: {
          offset: -15,
        },
      };
      const cmsAlarmConfig4 = {
        data: cms_alarm_list,
        xField: 'count',
        yField: 'user',
        seriesField: 'user',
        legend: {
          position: 'top-left',
        },
      };
      const cloudAccountConfig = {
        appendPadding: 10,
        data: cloud_account_list,
        angleField: 'count',
        colorField: 'platform',
        radius: 1,
        innerRadius: 0.64,
        meta: {
          value: {
            formatter: (v) => `${v} ¥`,
          },
        },
        label: {
          type: 'inner',
          offset: '-50%',
          style: {
            textAlign: 'center',
          },
          autoRotate: false,
          content: '{value}',
        },
        statistic: {
          title: {
            offsetY: -4,
            customHtml: (container, view, datum) => {
              const { width, height } = container.getBoundingClientRect();
              const d = Math.sqrt(Math.pow(width / 2, 2) + Math.pow(height / 2, 2));
              const text = datum ? datum.platform : '总计';
              return renderStatistic(d, text, {
                fontSize: 16,
              });
            },
          },
          content: {
            offsetY: 4,
            style: {
              fontSize: '16px',
            },
            customHtml: (container, view, datum, data) => {
              const { width } = container.getBoundingClientRect();
              const text = datum ? `${datum.count}` : `${data.reduce((r, d) => r + d.count, 0)}`;
              return renderStatistic(width, text, {
                fontSize: 16,
              });
            },
          },
        },
        // 添加 中心统计文本 交互
        interactions: [
          {
            type: 'element-selected',
          },
          {
            type: 'element-active',
          },
          {
            type: 'pie-statistic-active',
          },
        ],
      };

      const myStyle = {marginTop: "20px"}
      const myCard = {fontSize: "10px", marginTop: "-15px"}
      const myCardLeft = {marginLeft: "6px"}
      const myCardRight = {marginRight: "10px"}
      const myFont = {color: "#848484"}
      const myFont1 = {color: "#848484", height: "50px",  textAlign: 'center'}

      const myAlarm = {height: "27px", marginTop: "13px"}
      const myDivider = {margin: "10px 0"}
      const myBusinessAlarmChart = {height: '300px', width: "480px", marginLeft: "-80px"}
      const myCmsAlarmChart = {height: '280px', width: "430px", marginLeft: "20px"}
      const myCloudAccountChart = {height: '300px', width: "300px", marginLeft: "30px"}

      const myAlarmUp = {color: 'red'}
      const myAlarmDown = {color: 'green'}
      var alarm_week_percent = alarm_request_week_percent.indexOf('⬇') ? <span style={myAlarmUp}>{alarm_request_week_percent}</span> : <span style={myAlarmDown}>{alarm_request_week_percent}</span>
      var alarm_day_percent = alarm_request_day_percent.indexOf('⬇') ? <span style={myAlarmUp}>{alarm_request_day_percent}</span> : <span style={myAlarmDown}>{alarm_request_day_percent}</span>

      return (
        <div>
          <div style={myStyle}>
            <Row gutter={[16, 16]}>
              <Col span={6}>
                <Card style={myCard} >
                  <Statistic
                    title="访问量"
                    value={total_request}
                    // precision={2}
                    // valueStyle={{ color: '#3f8600' }}
                    suffix=""
                  />
                  <TinyArea {...requestConfig} />
                  <Divider style={myDivider} />
                  <span style={myFont}>
                      今日访问: {total_request_today}
                  </span>
                </Card>
            </Col>
            <Col span={6}>
                <Card style={myCard}>
                    <Statistic
                      title="助手调用"
                      value={robot_request}
                      // precision={2}
                      // valueStyle={{ color: '#3f8600' }}
                      suffix=""
                    />
                    <TinyColumn {...robotConfig} />
                    <Divider style={myDivider} />
                    <Row>
                      <Col span={8}><span style={myFont}>单聊: {robot_request_today_single}</span></Col>
                      <Col span={16}><span style={myFont}>群聊: {robot_request_today_many}</span></Col>
                    </Row>    
                </Card>
            </Col>
            <Col span={6}>
              <Card style={myCard}>
                  <Statistic
                    title="告警量"
                    value={alarm_request}
                    // precision={2}
                    valueStyle={{ color: '#3f8600' }}
                    // prefix={<ArrowUpOutlined />}
                    suffix=""
                  />
                  <div style={myAlarm}>
                    <Row>
                      <Col span={8}>周同比: {alarm_week_percent}</Col>
                      <Col span={8}>日环比: {alarm_day_percent}</Col>
                    </Row>
                  </div>

                  <Divider style={myDivider} />
                  <Row>
                    <Col span={8}><span style={myFont}>阈值: {alarm_request_threshold}</span></Col>
                    <Col span={8}><span style={myFont}>事件: {alarm_request_event}</span></Col>
                    <Col span={8}><span style={myFont}>容器: {alarm_request_sls}</span></Col>
                  </Row>    
              </Card>
            </Col>
            <Col span={6}>
                <Card style={myCard}>
                    <Statistic
                        title="审批量"
                        value={approval_request}
                        // precision={2}
                        // valueStyle={{ color: '#3f8600' }}
                        suffix=""
                    />
                    <TinyArea {...approvalConfig} />
                    <Divider style={myDivider} />
                    <Row>
                        <Col span={16}><span style={myFont}>运维账户: {approval_request_account}</span></Col>
                        <Col span={8}><span style={myFont}>域名解析: {approval_request_domain}</span></Col>
                    </Row>   
                </Card>
            </Col>
          </Row>
        </div>
        <div style={myStyle}>
            <Row>
                <Col span={18}>
                  <Card style={myCardRight}>
                    <Row>
                      <Col span={10}>
                        <div style={myFont1}>业务线告警数量</div>
                        <Rose {...businessAlarmConfig} style={myBusinessAlarmChart}/>
                      </Col>

                      <Col span={14}>
                        <div style={myFont1}>负责人短信数量</div>
                        <Row>
                          <Col span={6}>
                            <List
                              size="small"
                              split={false}
                              itemLayout="horizontal"
                              dataSource={cms_alarm_list}
                              renderItem={item => (
                                <List.Item>
                                <List.Item.Meta
                                  avatar={<Avatar src={item.icon} />}
                                  title={<a href="https://ant.design">{item.user}</a>}
                                  description={item.count}
                                />
                              </List.Item>
                              )}
                          />
                          </Col>
                          <Col span={18}>
                          <Bar {...cmsAlarmConfig4} style={myCmsAlarmChart}/>
                          </Col>                             
                        </Row>
                      </Col>
                    </Row>
                  </Card>
                </Col>

                <Col span={6}>
                  <Card style={myCardLeft}>
                    <Row>
                    <Col span={24}>
                        <div style={myFont1}>云平台账户汇总</div>
                        <Pie {...cloudAccountConfig} style={myCloudAccountChart} />
                      </Col>
                    </Row>
                  </Card>
                </Col>
            </Row>    
          </div>
        </div>      
      )
    }
}

export default Dashboard;